package com.splic.product.facade;

import com.splic.common.core.DeviceContext;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.*;
import com.splic.product.dto.DeviceDto;
import com.splic.product.dto.DeviceReportResultDto;
import com.splic.product.mapper.DeviceProductMapper;
import com.splic.product.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

/**
 * ==========================
 * 开发：singe
 * 创建时间：2022-03-25 21:40
 * 版本: 1.0
 * 描述：TODO
 * ==========================
 */
@Component
@Slf4j
public class DeviceFacade {

    @Autowired
    private DeviceService deviceServiceImpl;
    @Autowired
    private ProductService productServiceImpl;
    @Autowired
    private EventService eventServiceImpl;
    @Autowired
    private UserActiveService userActiveServiceImpl;
    @Autowired
    private UserService userServiceImpl;

    @Autowired
    private DeviceProductMapper deviceProductMapper;

    /**
     * 用户主动上报新增或活跃
     * @param device
     * @return
     */
    public DeviceReportResultDto reportInfo(DeviceDto device) {
        if (StringUtils.isNotEmpty(device.getPackageKey())){
            Optional<Product> optionalProduct = Optional.ofNullable(productServiceImpl.getByPackageKey(device.getPackageKey()));
            optionalProduct.ifPresent(product ->device.setProductId(product.getId()));
        }

        if (StringUtils.isNotEmpty(device.getUserIdentify())){
            Optional<User> optionalProduct = Optional.ofNullable(userServiceImpl.getByUserIdentify(device.getUserIdentify()));
            optionalProduct.ifPresent(user ->device.setUserId(user.getId()));
        }

        //获取设备标识和设备id
        getDeviceIdentify(device);
        if ("02:00:00:00:00:00".equals(device.getMac())) {
            device.setMac(null);
        }
        if ("0000000000000000".equals(device.getAndroidId())) {
            device.setAndroidId(null);
        }
        if ("00000000-0000-0000-0000-000000000000".equals(device.getOaid()) || "00000000000000000000000000000000".equals(device.getOaid())) {
            device.setOaid(null);
        }
        deviceServiceImpl.saveOrUpdate(device);

        //保存用户活跃
        saveUserActive(device);

        //保存事件
        saveEvent(device);

        DeviceReportResultDto dto = new DeviceReportResultDto();
        dto.setDeviceIdentify(device.getDeviceIdentify());
        dto.setShowAdvert(true);
        return dto;
    }


    /**
     * 保存用户活跃
     * @param device
     */
    public void saveUserActive(Device device) {
        try {
            UserActive userActive = new UserActive();
            userActive.setDate(new Date());
            userActive.setDeviceId(device.getId());
            userActive.setProductId(device.getProductId());
            userActive.setUserId(device.getUserId());
            userActiveServiceImpl.insert(userActive);
        }catch (Exception e){

        }
    }

    /**
     * 保存用户事件
     */
    public void saveEvent(DeviceDto device){
        if (StringUtils.isNotEmpty(device.getEvent())){
            Event event = new Event();
            event.setDeviceId(device.getId());
            event.setUserId(device.getUserId());
            event.setEvent(device.getEvent());
            eventServiceImpl.saveOrUpdate(event);
        }
    }

    /**
     * 用户主动上报新增或活跃
     * @param device
     * @return
     */
    public String interfaceNeedInfo(DeviceDto device) {

        if (StringUtils.isNotEmpty(device.getPackageKey())){
            Optional<Product> optionalProduct = Optional.ofNullable(productServiceImpl.getByPackageKey(device.getPackageKey()));
            optionalProduct.ifPresent(product ->device.setProductId(product.getId()));
        }

        if (StringUtils.isNotEmpty(device.getUserIdentify())){
            Optional<User> optionalProduct = Optional.ofNullable(userServiceImpl.getByUserIdentify(device.getUserIdentify()));
            optionalProduct.ifPresent(user ->device.setUserId(user.getId()));
        }
        //获取设备标识和设备id
        getDeviceIdentify(device);
        if ("02:00:00:00:00:00".equals(device.getMac())) {
            device.setMac(null);
        }
        if ("0000000000000000".equals(device.getAndroidId())) {
            device.setAndroidId(null);
        }
        if ("00000000-0000-0000-0000-000000000000".equals(device.getOaid()) || "00000000000000000000000000000000".equals(device.getOaid())) {
            device.setOaid(null);
        }
        if (device.getId() == null) {
            log.error("关键参数未查询到设备，新增中。。。:产品{}设备{}", DeviceContext.getProductPackageKey(), device);
        }
        deviceServiceImpl.saveOrUpdate(device);

        saveUserActive(device);
        return device.getDeviceIdentify();
    }


    /**
     * 获取设备标识和设备id
     * @param device
     * @return
     */
    public Device getDeviceIdentify(Device device){
        Device deviceQuery = null;
        if (StringUtils.isNotEmpty(device.getDeviceIdentify())){
            deviceQuery = deviceServiceImpl.getByDeviceIdentify(device.getDeviceIdentify());
            selectDevice(deviceQuery,device);
        }else {
            if (device.getId() == null && StringUtils.isNotEmpty(device.getAndroidId())) {
                deviceQuery = deviceServiceImpl.getByAndroidId(device.getAndroidId());
                selectDevice(deviceQuery, device);
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getMac())) {
                deviceQuery = deviceServiceImpl.getByMac(device.getMac());
                selectDevice(deviceQuery, device);
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getOaid())) {
                deviceQuery = deviceServiceImpl.getByOaid(device.getOaid());
                selectDevice(deviceQuery, device);
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getVaid())) {
                deviceQuery = deviceServiceImpl.getByVaid(device.getVaid());
                selectDevice(deviceQuery, device);
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getGaid())) {
                deviceQuery = deviceServiceImpl.getByGaid(device.getGaid());
                selectDevice(deviceQuery, device);
            }
            if (device.getId() == null && StringUtils.isNotEmpty(device.getImei())) {
                deviceQuery = deviceServiceImpl.getByImei(device.getImei());
                selectDevice(deviceQuery, device);
            }
        }
        if (deviceQuery == null) {
            return device;
        }
        DeviceProduct deviceProduct = new DeviceProduct();
        deviceProduct.setDeviceId(device.getId());
        deviceProduct.setProductId(device.getProductId());
        deviceProduct.setCreateTime(new Date());
        deviceProductMapper.insert(deviceProduct);
        return deviceQuery;
    }


    /**
     *
     * @param deviceQuery
     * @param device
     */
    public void selectDevice(Device deviceQuery,Device device){
        if(deviceQuery != null){
            device.setId(deviceQuery.getId());
            device.setDeviceIdentify(deviceQuery.getDeviceIdentify());
            if(deviceQuery.getUserId() == null && device.getUserId() != null){
                deviceQuery.setUserId(device.getUserId());
                deviceServiceImpl.update(deviceQuery);
            }
            device.setUserId(deviceQuery.getUserId());
        }
    }
}
